<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 用户管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <div class="container">
            <div class="handle-box">
                <el-button
                    type="danger"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                    :disabled="isDisabled"
                >批量删除</el-button>
                <el-button
                    type="success"
                    icon="el-icon-plus"
                    class="handled-del mr10"
                    @click="handleAdd"
                >添加</el-button>
                <el-input v-model="query.username" placeholder="请输入用户名称" class="handle-input mr10"></el-input>
                <el-button 
                    type="primary"
                    icon="el-icon-search"
                    class="handled-del mr10"
                    @click="handleSearch"
                >搜索</el-button>
                 <el-select v-model="query.status" class="handle-select mr10" placeholder="用户状态" @change="statusChange">
                    <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
                 <el-date-picker
                    class="handle-date mr10"
                    v-model="date"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="dateChange"
                    value-format="yyyy-MM-dd">
                    </el-date-picker>
                <el-button
                    type="info"
                    icon="el-icon-download"
                    class="handled-del mr10"
                    @click="handleImport"
                >导入</el-button>
                <el-button
                    type="warning"
                    icon="el-icon-download"
                    class="handled-del mr10"
                    @click="handleExport"
                >导出</el-button>
            </div>
            <el-table
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0,0,0,0.8)"
                :data="userList"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange">

                <el-table-column
                    type="selection"
                    width="55"
                    align="center">
                </el-table-column>
                <el-table-column
                    prop="account"
                    label="账号"
                    align="center">
                </el-table-column>
                <el-table-column
                    prop="username"
                    label="姓名"
                    align="center">
                </el-table-column>
                <el-table-column
                    prop="email"
                    label="邮箱"
                    align="center">
                </el-table-column>
                 <el-table-column
                    prop="telephone"
                    label="手机号"
                    align="center">
                </el-table-column>
                 <el-table-column
                    prop="sex"
                    label="性别"
                    align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.sex===0" type="success">男</el-tag>
                        <el-tag v-else type="warning">女</el-tag>
                    </template>
                </el-table-column>
                 <el-table-column
                    prop="avatar"
                    label="头像"
                    align="center">
                    <template slot-scope="scope">
                        <el-image 
                            class="table-td-thumb"
                            :src="scope.row.avatar"
                            :preview-src-list="[scope.row.avatar]"
                        ></el-image>
                    </template>
                </el-table-column>
                 <el-table-column
                    prop="status"
                    label="状态"
                    align="center">
                    <template slot-scope="scope">
                         <el-tag v-if="scope.row.status===0" type="success">正常</el-tag>
                        <el-tag v-else type="danger">停用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="createTime"
                    label="注册时间"
                    align="center">
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="220"
                    align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-success"
                            class="green"
                            @click="handleReset(scope.$index, scope.row)">重置密码</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                        @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                     layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!--  添加编辑弹出框  -->
        <el-dialog
            :title="title"
            :visible.sync="visible"
            width="50%">

            <el-form :model="form" :rules="rules" ref="form" label-width="70px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="账号" prop="account">
                            <el-input v-model="form.account" :disabled="acDisabled" @blur="checkAccount"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="username">
                            <el-input v-model="form.username"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="密码" prop="password">
                            <el-input type="password" v-model="form.password" :disabled="pwdDisabled"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="form.email"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="telephone">
                            <el-input v-model="form.telephone"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="sex">
                            <el-select v-model="form.sex" placeholder="请选择">
                                <el-option
                                v-for="item in sexOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                 <el-row :gutter="20">
                    <el-col :span="20">
                        <el-form-item label="状态">
                            <el-radio  v-model="form.status" label="0">正常</el-radio>
                            <el-radio  v-model="form.status" label="1">禁用</el-radio>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <el-row :gutter="20">
                    <el-col :span="20">
                        <el-form-item label="头像" prop="avatar">
                            <el-upload
                                class="avatar-uploader"
                                ref="upload"
                                action="abc"
                                :auto-upload="false"
                                :on-change="handleChange"
                                :show-file-list="false">
                                <img v-if="form.avatar" :src="form.avatar" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>

               <el-row :gutter="20">
                    <el-col :span="20">
                        <el-form-item label="备注" prop="remark">
                            <el-input 
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            v-model="form.remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
           </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </el-dialog>

        <!--  导入用户excel  -->
        <el-dialog
            title="用户导入"
            :visible.sync="excelVisible"
            width="30%"
            :before-close="excelClose"
            >
            <el-upload
                class="upload-demo"
                drag
                ref="excelUpload" 
                action="abc"
                :on-change="excelChange"
                :auto-upload="false"
                :multiple="false"
                :limit=1
                accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="" slot="tip"><el-link type="primary" @click="handleTemplate">模板下载</el-link></div>
                <div class="el-upload__tip" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
            </el-upload>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelExcel">取 消</el-button>
                <el-button type="primary" @click="importExcel">确 定</el-button>
            </span>
            </el-dialog>

    </div>
</template>

<script>
import {getList,delUser,getUser,updateUser,addUser,delAllUser,resetPwd,checkAccount,exportUser,importUser} from '@/api/basic/user'


export default {
    name: "User",
    data () {
        return {
            // 查询参数
            query: {
                username: '',
                status: null,
                startDate: '',
                endDate: '',
                pageIndex: 1,
                pageSize: 3
            },
            // 遮罩层
            loading: false,
            // 用户列表
            userList: [],
            // 用户总数量
            pageTotal: 0,
            // 表单标题
            title: '',
            // 是否显示表单
            visible: false,
            // 表单对象
            form: {
                userId: '',
                account: '',
                username: '',
                password: '',
                email: '',
                telephone: '',
                sex: '',
                avatar: '',
                status: '',
                remark: ''
            },
            // 校验规则
            rules: {
                account: [{required: true, message: '请填写账号',trigger: 'blur'}],
                username: [{required: true, message: '请填写名称',trigger: 'blur'}],
                password: [{required: true, message: '请填写密码',trigger: 'blur'}],
                email: [{required: true, message: '请填写邮箱',trigger: 'blur'}],
                telephone: [{required: true, message: '请填写手机号',trigger: 'blur'}],
                sex: [{required: true, message: '请选择性别',trigger: 'blur'}],
            },
            // 用户性别
            sexOptions: [
                {value: '0',label: '男'}, 
                {value: '1',label: '女'}, 
            ],
            // 存放批量删除用户
            multipleSelection: [],
            // 账号是否禁用，不可编辑
            acDisabled: false,
            // 密码是否禁用，不可编辑
            pwdDisabled: false,
            // 账号可使用，能添加，账号已存在，不能添加
            flag: true,
            // 用户头像
            avatarFile: null,
            // 批量删除按钮是否可以点击
            isDisabled: true,
            // 是否显示导入excel
            excelVisible: false,
            // excel文件
            userExcelFile: null,
            // 用户状态
            statusOptions: [
                {value: null,label: '请选择'},
                {value: '0',label: '正常'},
                {value: '1',label: '停用'}
            ],
            date: ''
        }
    },
    created () {
        // 获取用户列表
        this.getData();
    },
    watch: {
        // 监听最后一页删除最后一条数据时，当前页不变情况
        pageTotal(){
            if(this.pageTotal==(this.query.pageIndex-1)*this.query.pageSize && this.pageTotal!=0){
                this.query.pageIndex-=1;
                this.getData();
            }
        }
    },
    methods: {
        // 获取用户列表
        getData(){
            this.loading = true;
            getList(this.query).then(res => {
                // 过滤用户没有选择头像
                this.userList = res.data.records.map((user)=>{
                    if(user.avatar === ''){
                        user.avatar = require('@/assets/img/img.jpg');
                    }else{
                        user.avatar = "/api"+user.avatar;
                    }
                    return user;
                })
                this.pageTotal = res.data.total;
                this.loading = false;
                
            })
        },
        // 批量删除
        delAllSelection(){
            this.$confirm('确定要删除吗?','提示',{
                type: 'warning'
            }).then(()=>{
                const length = this.multipleSelection.length;
                let userIds = '';
                for(let i=0;i<length-1;i++){
                    userIds += this.multipleSelection[i].userId + ',';
                }
                userIds += this.multipleSelection[length-1].userId;

                delAllUser(userIds).then(res => {
                    this.$message.success(res.message);
                    this.multipleSelection = [];
                    this.getData();
                })
            }).catch(()=>{

            })
        },
        // 添加
        handleAdd(){
            this.reset();
            this.title = '添加用户';
            this.acDisabled = false;
            this.pwdDisabled = false;
        },
        // 搜索
        handleSearch(){
            this.$set(this.query,'pageIndex',1);
            this.getData();
        },
        // 当选择项发生变化时会触发该事件  多选checkbox
        handleSelectionChange(val){
            this.multipleSelection = val;
            if(this.multipleSelection.length === 0){
                this.isDisabled = true;
            }else{
                this.isDisabled = false;
            }
        },
        // 重置密码
        handleReset(index,row){
            this.$confirm('是否重置密码','提示',{
                type: 'warning'
            }).then(()=>{
                resetPwd(row.userId).then(res=>{
                    this.$message.success(res.message);
                })
            })
        },
        // 编辑
        handleEdit(index,row){
            new Promise((resolve,reject)=>{
                this.reset();
                resolve();
            }).then((res)=>{
                // this.form = JSON.parse(JSON.stringify(row));
                this.form = {...row};
            }).catch((err)=>{})
            
            this.flag = true;
            this.title = '编辑用户';
            this.acDisabled = true;
            this.pwdDisabled = true;
        },
        // 删除
        handleDelete(index,row){
            this.$confirm('确定要删除吗?','提示',{
                type: 'warning'
            }).then(()=>{
                delUser(row.userId).then(res => {
                    this.$message.success(res.message);
                    this.getData();
                }).catch(()=>{})
            }).catch(()=>{})
              
        },
        // 改变当前页时会触发该事件
        handlePageChange(pageIndex){
            this.$set(this.query, 'pageIndex', pageIndex);
            this.getData();
        },
        // 取消
        cancel(){
            this.reset();
            this.visible = false;
        },
        // 提交表单
        submitForm(){
            if(this.flag){
                this.$refs["form"].validate(valid => {
                    if(valid){
                        let formData = new FormData();
                            formData.append('account',this.form.account);
                            formData.append('username',this.form.username);
                            formData.append('password',this.form.password);
                            formData.append('email',this.form.email);
                            formData.append('telephone',this.form.telephone);
                            formData.append('sex',this.form.sex);
                            formData.append('avatar',this.form.avatar);
                            formData.append('status',this.form.status);
                            formData.append('remark',this.form.remark);
                            if(this.avatarFile != null)
                                formData.append('avatarFile',this.avatarFile.raw);
                        if(this.form.userId != undefined){
                            // 更新用户
                            formData.append('userId',this.form.userId);
                            updateUser(formData).then(res => {
                                this.$message.success(res.message);
                                this.visible = false;
                                this.getData();
                            })
                        }else{
                            // 添加用户
                            addUser(formData).then(res => {
                                this.$message.success(res.message);
                                this.visible = false;
                                this.getData();
                            })
                        }
                        this.avatarFile = null;
                    }
                })
            }else{
                this.$message.error('账号已存在');
            }

        },
        // 表单重置
        reset(){
            this.visible = true;
            this.form = {
                account: undefined,
                username: undefined,
                password: undefined,
                email: undefined,
                telephone: undefined,
                sex: undefined,
                avatar: undefined,
                status: '0',
                remark: ''
            }
            this.$nextTick(() => {
                this.$refs.form.resetFields();
            })
            
        },
        // 监听账号input 失去焦点事件
        checkAccount(event){
            checkAccount(this.form.account).then(res=>{
                if(res.code === 400){
                    this.$message.error(res.message);
                    this.flag = false;
                }else{
                    this.flag = true;
                }
            })
        },
        // 用户头像上传
        handleChange(file,fileList){
            // const isJPG = file.raw.type === 'image/png';
            const isLt2m = file.size /1024/1024<2;
            // if(!isJPG){
            //     this.$message.error('上传头像图片只能是JPG格式');
            // }
            if(!isLt2m){
                this.$message.error('上传头像图片大小不能超过2MB!');
            }
            this.form.avatar = URL.createObjectURL(file.raw);
            this.avatarFile = file;
            // return isJPG && isLt2m;
            return true;
        },
        // 用户导出excel
        handleExport(){
            this.$confirm('是否导出所有用户数据项','提示',{
                type: 'warning'
            }).then(()=>{
                exportUser().then(res => {
                    this.download(res.data);
                })
                
            }).catch(()=>{

            })
        },
        // 点击导入按钮，显示导入dialog
        handleImport(){
            this.excelVisible = true;
        },
        // 用户模板下载
        handleTemplate(){
            this.templateDownload('用户模板.xls');
        },
        // 取消excel dialog
        cancelExcel(){
            this.excelVisible = false;
            this.resetExcel();
        },
        // 右上角关闭excel
        excelClose(){
            this.excelVisible = false;
            this.resetExcel();
        },
        // 用户导入excel
        importExcel(){
            if(this.userExcelFile === null){
                this.$message.error('请选择文件')
            }else{
                this.$confirm('是否要导入用户数据','提示',{
                    type: 'warning'
                }).then(()=>{
                    let formData = new FormData();
                    formData.append('userExcelFile',this.userExcelFile);

                    importUser(formData).then(res => {
                        this.$message.success('导入成功');
                        this.getData();
                        this.excelVisible = false;
                        this.resetExcel();
                    })
                })
            }
        },
        // 用户选择excel文件
        excelChange(file, fileList){
            this.userExcelFile = file.raw;
        },
        // 重置excel dialog
        resetExcel(){
            this.userExcelFile = null;
            this.$refs.excelUpload.clearFiles();
        },
        // 用户状态下拉改变
        statusChange(){
            this.getData();
        },
        // 用户注册日期改变
        dateChange(){
            if(this.date != null){
                this.query.startDate = this.date[0];
                this.query.endDate = this.date[1];
            }else{
                 this.query.startDate = '';
                this.query.endDate = '';
            }
           
            this.getData();
           
        }
    }
}
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 200px;
    display: inline-block;
}
.handle-select {
    width: 120px;
    display: inline-block;
}
.handle-date {
    width: 250px;
    
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.green {
    color: green;
}
.mr10 {
    margin-right: 10px;
    margin-top: 10px;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}

.el-row {
    margin-bottom: 20px;
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-upload__tip {
      color: red;
  }
</style>